﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System.Runtime.Serialization;
using System;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrainTechLLC.ThreadSafeObjects;

namespace BrainTechLLC
{
	public static partial class CommandFactory
	{
        [MethodVisible]
		public static SingleModification AddOrSubtractFromProperty(string property, int amount)
		{
			return new SingleModification()
			{
				ChangeToApply = (o1, args1, signals1) =>
					 {
						 GameChar c = (o1 as GameChar);
						 IdentifierAndValue max = c.ThingProperties.GetReference("Max" + property);
						 int maxAmount = (max != null) ? Convert.ToInt32(max.Value) : int.MaxValue;
                         int oldValue = c.GetProperty<int>(property);
						 int newTotal = oldValue + amount;

						 if (newTotal > maxAmount)
							 newTotal = maxAmount;

                         if (oldValue == newTotal)
                             return;

                         IdentifierAndValue oldProp = c.ThingProperties.GetReference(property);

                         if (oldProp == null)
                         {
                             c.AddOrSetProperty(property, newTotal);
                         }
                         else
                         {
                             Interlocked.Exchange(ref oldProp._value, newTotal);
                         }

                         StringAndNumeric msg = new StringAndNumeric() { Text = property, Numeric = newTotal };
                         c.Notify(new Notification(msg));
					 }
			};
		}
	}
}
